/**
 * Copyright (C), 2001-2031, www.bosssof.com.cn
 * FileName: ReceiveServerFileHandle.java
 * Author: ckj
 * Date: 2024/7/21 下午9:27
 * Description:
 * 用户接收文件的操作
 * History:
 * Date          Author   Version  Desc
 * 2024-01-01    bosssoft  1.0.0   initialize this file
 */
package com.bosssoft.handle;

import com.bosssoft.issue.BaseIssue;
import com.bosssoft.issue.ReceiveServerFileIssue;
import com.bosssoft.message.ReceiveServerFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;

import static com.bosssoft.client.Client.USER_FILE_PATH;


/**
 * @author ckj
 */
public class ReceiveServerFileHandle implements BaseHandle {

    private static final Logger logger = LoggerFactory.getLogger(ReceiveServerFileHandle.class);

    /**
     *
     * @author ckj
     * @date 2024/07/22 上午9:26
     * 处理获取文件
     */
    @Override
    public void handle(BaseIssue issue) throws IOException {
        ReceiveServerFileIssue receiveServerFileIssue = (ReceiveServerFileIssue) issue;
        ReceiveServerFile receiveServerFile = (ReceiveServerFile) receiveServerFileIssue.getMessage();
        File userDir = new File( USER_FILE_PATH + receiveServerFileIssue.userName);
        if (!userDir.exists()) {
            userDir.mkdir();
        }
        File userNewFile = new File(USER_FILE_PATH + receiveServerFileIssue.userName + File.separator + receiveServerFile.getFileName());
        if (!userDir.exists()) {
            if(userNewFile.createNewFile()) {
                logger.info("文件创建成功");
            } else {
                logger.error("文件创建失败");
            }
        }
        try (BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(userNewFile.toPath())))) {
            receiveServerFile.getFileContent().forEach(everyLine -> {
                try {
                    bufferedWriter.write(everyLine);
                    bufferedWriter.flush();
                } catch (IOException e) {
                    logger.error("Error writing file");
                }
            });
        }
    }
}